package etcd

import (
	"fmt"
	clientv3 "go.etcd.io/etcd/client/v3"
	"purchase-mall/conf"
	"time"
)

var etcd *clientv3.Client

// Init 初始化Etcd连接
func Init(cfg *conf.EtcdConfig) (err error) {
	fmt.Printf("Etcd Switch %v\n", cfg.Switch)
	if cfg.Switch == false {
		return nil
	}
	dsn := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)
	etcd, err = clientv3.New(clientv3.Config{
		Endpoints:   []string{dsn},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		//fmt.Printf("connect to etcd failed, err:%v\n", err)
		return err
	}
	//fmt.Println("connect to etcd success")
	//// put
	//ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	//_, err = etcd.Put(ctx, "lmh", "lmh")
	//cancel()
	//if err != nil {
	//	fmt.Printf("put to etcd failed, err:%v\n", err)
	//	return
	//}
	//// get
	//ctx, cancel = context.WithTimeout(context.Background(), time.Second)
	//resp, err := etcd.Get(ctx, "lmh")
	//cancel()
	//if err != nil {
	//	fmt.Printf("get from etcd failed, err:%v\n", err)
	//	return
	//}
	//for _, ev := range resp.Kvs {
	//	fmt.Printf("%s:%s\n", ev.Key, ev.Value)
	//}
	return nil
}

// Close 关闭MySQL连接
func Close() {
	_ = etcd.Close()
}
